/**
 *　　　　　　　　┏┓　　　┏┓+ +
 *　　　　　　　┏┛┻━━━┛┻┓ + +
 *　　　　　　　┃　　　　　　　┃
 *　　　　　　　┃　　　━　　　┃ ++ + + +
 *　　　　　　 ████━████ ┃+
 *　　　　　　　┃　　　　　　　┃ +
 *　　　　　　　┃　　　┻　　　┃
 *　　　　　　　┃　　　　　　　┃ + +
 *　　　　　　　┗━┓　　　┏━┛
 *　　　　　　　　　┃　　　┃
 *　　　　　　　　　┃　　　┃ + + + +
 *　　　　　　　　　┃　　　┃　　　　Code is far away from bug with the animal protecting
 *　　　　　　　　　┃　　　┃ + 　　　　神兽保佑,代码无bug
 *　　　　　　　　　┃　　　┃
 *　　　　　　　　　┃　　　┃　　+
 *　　　　　　　　　┃　 　　┗━━━┓ + +
 *　　　　　　　　　┃ 　　　　　　　┣┓
 *　　　　　　　　　┃ 　　　　　　　┏┛
 *　　　　　　　　　┗┓┓┏━┳┓┏┛ + + + +
 *　　　　　　　　　　┃┫┫　┃┫┫
 *　　　　　　　　　　┗┻┛　┗┻┛+ + + +
 */


#import "PywSdk+pay.h"
#import <objc/runtime.h>
#import "PywPayViewController.h"
#import "PywNavgationController.h"
#import "PywPlatformMain.h"
#import "PywMBProgressHUD+Pyw.h"
#import "MutableDictionary.h"
#import "PywIAPPayManager.h"
#import "PywGetOrderInfoApi.h"
#import "PywCommonManager.h"
#import "PywComInitApi.h"

@interface PywSdk()
@property (nonatomic, weak)UIWindow *tmpWindow;
@property (nonatomic,strong) PywGetOrderInfoApi *getOrderInfoApi;
@property (nonatomic,strong) PywComInitApi *mpayInitApi;
@end

@implementation PywSdk (pay)

static char KeyOrderInfo = 'keyOrderInfo';
static char KeyPayInitApi = 'KeyPayInitApi';

#pragma mark - Public Actions

/**
 集合SDK直接调用 朋友玩渠道支付
 
 @param payInfo 支付信息和接口请求配置参数信息
 */
- (void)pywChannelPay:(NSDictionary *)payInfo
{
    if (payInfo.count > 0) {
        /**
         *  获取并设置相关参数:由channel_params字典包装传入
         *      1. 设置登陆账号类型，为“游戏账号登陆”，设置执行支付类型为"聚合"调用；
         *      2. 赋值account、token、gameid、gamekey、apisecret为传入的值；
         *      3. 设置支付方式，由聚合传入的charge_type控制：
         *        （1）当charge_type为1时，使用“定额支付”；
         *        （2）当charge_type为2时，使用“任意支付”。
         */
        NSDictionary *channel_params = [payInfo objectForKey:@"channel_params"];
        [PywPlatformMain sharedPlatformMain].accountType = UserType_Account;
        [PywPlatformMain sharedPlatformMain].perfromPayType = PerfromPayType_Common;
        [PywPlatformMain sharedPlatformMain].account = [channel_params objectForKey:@"account"];
        [PywPlatformMain sharedPlatformMain].token = [channel_params objectForKey:@"token"];
        [PywAppInfo sharedAppInfo].gameKey = [channel_params objectForKey:@"gamekey"];
        [PywAppInfo sharedAppInfo].gameId = [channel_params objectForKey:@"gameid"];
        [PywAppInfo sharedAppInfo].apisecret = [channel_params objectForKey:@"apisecret"];
        [PywAppInfo sharedAppInfo].sdk_api_url = [channel_params objectForKey:@"sdk_api_url"];
        [PywAppInfo sharedAppInfo].sdk_pay_url =[channel_params objectForKey:@"sdk_pay_url"];
        NSString *type = [channel_params objectForKey:@"pyw_sdk_type"];
        [PywAppInfo sharedAppInfo].appType = [self changeToAppType:[type intValue]];
        NSString *charge_type = [channel_params objectForKey:@"charge_type"];
        
        // 先初始化，在调用支付
        [PywAppInfo sharedAppInfo].seriviceType = kAIFServicePro;
        [[PywCommonManager manager] changeWebViewUserAgnet];
        
        self.mpayInitApi = [PywComInitApi manager];
        [self.mpayInitApi requestInitWithSuccess:^(NSString *status, id anyObjct) {
            if ([charge_type isEqualToString:@"1"]) { // 定额支付
                
                [PywAppInfo sharedAppInfo].payType = PayTypeFix;
                [self startPayWithInfo:payInfo];
            }else if ([charge_type isEqualToString:@"2"]){ // 任意支付
                
                [PywAppInfo sharedAppInfo].payType = PayTypeAny;
                [self startPayWithInfo:payInfo];
            }
        } fail:^(NSError *error) {
            [PywMBProgressHUD hideHUD];
            [PywMBProgressHUD showError:@"请求失败!" toView:[UIApplication sharedApplication].keyWindow];
        }];
    }
}

-(AppType) changeToAppType:(int) i{
    if(i == 7){
        return APPTypeBOTAH;
    }else if(i == 6){
        return AppTypeFQ;
    }
    return AppTypePYW;
}

/**
 *  点击任意支付
 */
- (void)anyPay:(NSDictionary *)payInfo
{
    [PywAppInfo sharedAppInfo].payType = PayTypeAny;
    [self perfromPay:payInfo];
}
/**
 *  点击固定支付
 */
- (void)pay:(NSDictionary *)payInfo
{
    [PywAppInfo sharedAppInfo].payType = PayTypeFix;
    [self perfromPay:payInfo];
}

#pragma mark - Private Action
- (void)perfromPay:(NSDictionary *)payInfo
{
    if (![PywPlatformMain sharedPlatformMain].logined) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"友情提示"
                                                        message:@"请您先登录再进行支付操作"
                                                       delegate:self
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    [self startPayWithInfo:payInfo];
}

- (void)startPayWithInfo:(NSDictionary *)payInfo
{
    @try {
        [PywMBProgressHUD showMessage:@"正在支付..."];
        [self requestOrderInfo:^(NSDictionary *orderInfo) {
            NSLog(@"orderInfo: %@",orderInfo.description);
            [PywMBProgressHUD hideHUD];
            NSDictionary *orderInfoDict = [orderInfo objectForKey:@"data"];
            BOOL is_applepay = [[orderInfoDict objectForKey:@"is_applepay"] boolValue];
            [PywAppInfo sharedAppInfo].is_applepay = is_applepay;
            if ([PywAppInfo sharedAppInfo].is_applepay) {
                if ([PywAppInfo sharedAppInfo].payType == PayTypeAny) {
                    [PywMBProgressHUD showError:@"支付方式不可用!"];
                    return;
                }
                [[PywIAPPayManager manger] setUpPayInfoModel:payInfo];
            }else {
                NSString *coupon_count = [orderInfoDict objectForKey:@"coupon_count"];
                NSString *pay_type_order = [orderInfoDict objectForKey:@"pay_type_order"];
                NSString *pay_url = [orderInfoDict objectForKey:@"pay_url"];
                [PywAppInfo sharedAppInfo].pay_type_order = pay_type_order;
                
                MutableDictionary *dictionary = [[MutableDictionary alloc] initWithDictionary:payInfo];
                [dictionary setObject:coupon_count forKey:@"coupon_count"];
                [dictionary setObject:pay_url forKey:@"pay_url"];
                
                UIViewController *gameController = [UIApplication sharedApplication].keyWindow.rootViewController;
                PywPayViewController *payView = [[PywPayViewController alloc] initWithPayInfo:dictionary];
                PywNavgationController *nav = [[PywNavgationController alloc] initWithRootViewController:payView];
                [gameController presentViewController:nav animated:YES completion:^{
                    
                }];
            }
        }];
    } @catch (NSException *exception) {
        PLog(@"二次初始化失败");
        [PywMBProgressHUD hideHUD];
        [PywMBProgressHUD showError:@"生成订单失败!"];
    } @finally {
        
    }
}

#pragma mark - Request
/**
 *  请求订单信息（根据返回结果判断苹果内购）
 */
- (void)requestOrderInfo:(void(^)(NSDictionary *))block
{
    self.getOrderInfoApi = [PywGetOrderInfoApi manager];
    [self.getOrderInfoApi getOrderInfo:^(NSString *status, id anyObjct) {
        [PywMBProgressHUD hideHUD];
        NSDictionary *orderInfo = (NSDictionary *)anyObjct;
        if (block) {
            block(orderInfo);
        }
    } fail:^(NSError *error) {
        [PywMBProgressHUD hideHUD];
        [PywMBProgressHUD showError:@"生成订单失败!"];
    }];
}

- (PywGetOrderInfoApi *)getOrderInfoApi
{
    return objc_getAssociatedObject(self, &KeyOrderInfo);
}

-(void)setGetOrderInfoApi:(PywGetOrderInfoApi *)getOrderInfoApi
{
    objc_setAssociatedObject(self, &KeyOrderInfo, getOrderInfoApi,OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}


- (PywComInitApi *)mpayInitApi
{
    return objc_getAssociatedObject(self, &KeyPayInitApi);
}
- (void)setMpayInitApi:(PywComInitApi *)mpayInitApi
{
    objc_setAssociatedObject(self, &KeyPayInitApi, mpayInitApi, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}


@end
